using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using Microsoft.Xna.Framework.Net;
using Microsoft.Xna.Framework.Storage;
using System.Reflection;


namespace DarkNeuron.Services.Log
{
	public class GameLog
	{
		protected static StreamWriter streamWriter;
		protected static TextWriter streamWriterDefaultConsole;
		public static string DirectoryPath { get; protected set; }


		public GameLog(string name)
		{
			// Error handle
			if (String.IsNullOrEmpty(name)) Console.WriteLine("GameLog|Warning:> name typeof(string) is null or empty!");
			// END Error handle


			Console.WriteLine("GameLog|Information:> New GameLog is being initialized...");

			string baseDir = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
			DirectoryPath = String.Format("{0}\\Log\\{1}", baseDir, name);
			// Creates new directory if directory doesn't already exists
			try
			{
				if (!Directory.Exists(DirectoryPath))
					Directory.CreateDirectory(DirectoryPath);
			}
			catch (ArgumentException e)
			{ Console.WriteLine("GameLog|Error:> Directory not created!\n{0}", e.ToString()); return; }
			// Redirects console to file stream
			try
			{
				streamWriterDefaultConsole = Console.Out;
				streamWriter = new StreamWriter(
					String.Format("{0}\\{1}{2}{3}{4}{5}{6}{7}.dnlco",
					DirectoryPath,
					name,
					DateTime.Now.Year.ToString(),
					DateTime.Now.Month.ToString(),
					DateTime.Now.Day.ToString(),
					DateTime.Now.Hour.ToString(),
					DateTime.Now.Minute.ToString(),
					DateTime.Now.Second.ToString()));
				streamWriter.AutoFlush = true;
				Console.SetOut(streamWriter);
			}
			catch (ArgumentException e)
			{ Console.WriteLine("GameLog|Error:> Console redirection failed!\n{0}", e.ToString()); return; }

			Console.WriteLine("GameLog|Information:> GameLog is successfully initialized.");
		}


		public static void CloseOutput()
		{
			try
			{
				// If stream writel is null then it is not initialized
				if (streamWriter != null)
				{
					streamWriter.Flush();
					streamWriter.Close();
					Console.SetOut(streamWriterDefaultConsole);
				}
			}
			catch (ArgumentException e)
			{ Console.WriteLine("GameLog|Error:> Error occured while closing console file stream!"); return; }
		}
	}
}